//
//  HttpRequest.m
//  MoneyLog
//
//  Created by Max on 11-1-30.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HttpRequest.h"
#import "SQLiteHelper.h"


@implementation HttpRequest

@synthesize buffer;
@synthesize connection;
@synthesize	progressAlertView;
@synthesize fileStream;

-(id) init{
	[super init];
	
	//init recieve buffer
	buffer=[[NSMutableData alloc] initWithLength: 0 ];
	
	return self;	
}

#pragma mark -
#pragma mark Actions

-(void) updateApp:(NSString*) urlStr{
	NSMutableURLRequest * request=[ [NSMutableURLRequest alloc] init]; 
    [request setURL:[NSURL URLWithString:urlStr]];
	
	//设置HTTP方法
	[request setHTTPMethod:@"GET"];
	
	NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentFolderPath = [searchPaths objectAtIndex: 0];
	NSString *tempDBFilePath = [documentFolderPath stringByAppendingPathComponent:
								@"moneylog.temp.db"];
	if (isRecv)
		return;
	
	self.fileStream = [NSOutputStream outputStreamToFileAtPath:tempDBFilePath append:NO];
	[fileStream open];
	
	
	connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];	
	if (connection) {
		self.progressAlertView = [[UIAlertView alloc] 
								  initWithTitle:@"数据更新" 
								  message:@"正在获取程序版本信息" 
								  delegate:self 
								  cancelButtonTitle:@"停止" 
								  otherButtonTitles:nil];	
		progressAlertView.tag = 0x8801;
		[progressAlertView show];
	}
}

- (void) stopReceive
{
    if (connection != nil) {
        [connection cancel];
        [connection release];
    }
    if (self.fileStream != nil) {
        [self.fileStream close];
        self.fileStream = nil;
    }
	isRecv = false;
}

- (BOOL)copyTempDBFile
{
	NSArray *searchPaths =
	NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentFolderPath = [searchPaths objectAtIndex: 0];
	NSString *tempDBFilePath = [documentFolderPath stringByAppendingPathComponent:
								@"moneylog.temp.db"];
	NSString *zipFilePath = [documentFolderPath stringByAppendingPathComponent:@"moneylog.zip"];
	//NSString *dbFilePath = [documentFolderPath stringByAppendingPathComponent:@"moneylog.db"];
	
	
	if ([[NSFileManager defaultManager] fileExistsAtPath: zipFilePath]) {
		BOOL delFile = [[NSFileManager defaultManager] 
						removeItemAtPath:zipFilePath
						error:nil];
		
		if (! delFile) {
			return NO;
		}
	}
	
	
	BOOL copiedBackupDb = [[NSFileManager defaultManager]
						   copyItemAtPath:tempDBFilePath
						   toPath:zipFilePath
						   error:nil];
	if (! copiedBackupDb) {
		return NO;
	}
	
	if ([[NSFileManager defaultManager] fileExistsAtPath: tempDBFilePath]) {
		BOOL delDB = [[NSFileManager defaultManager] 
					  removeItemAtPath:tempDBFilePath
					  error:nil];
		
		if (! delDB) {
			return NO;
		}
	}
/*	
	ZipArchive* za = [[ZipArchive alloc] init];
	if( [za UnzipOpenFile:zipFilePath] )
	{
		BOOL ret = [za UnzipFileTo:documentFolderPath overWrite:YES];
		[za UnzipCloseFile];
		
		if( NO==ret )
		{
			[za release];
			
			return NO;
		}
	}
	[za release];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath: zipFilePath]) {
		BOOL delFile = [[NSFileManager defaultManager] 
						removeItemAtPath:zipFilePath
						error:nil];
		
		if (! delFile) {
			return NO;
		}
	}
	
	if (![[NSFileManager defaultManager] fileExistsAtPath: dbFilePath]) {
		return NO;
	}
*/	
	return YES;
}

#pragma mark -
#pragma mark 异步请求

// 收到响应时, 会触发
// 你可以在里面判断返回结果, 或者处理返回的http头中的信息
- (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response {
	
	NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response; 
	
	isRecv = true;
	recvLen =0;
    if ((httpResponse.statusCode / 100) != 2) {
		NSLog(@"error");
    } else { 
		NSDictionary *headers = [httpResponse allHeaderFields];
		totalLen = [[headers objectForKey:@"Content-Length"] intValue];
		NSLog(@"数据大小：%d", totalLen); 
	}
	
	NSLog(@"状态码：%d", httpResponse.statusCode);	
}

// 每收到一次数据, 会调用一次
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data {
	[buffer appendData:data];
	
	NSInteger       dataLength;
    const uint8_t * dataBytes;
    NSInteger       bytesWritten;
    NSInteger       bytesWrittenSoFar;
    
	if (isRecv) {
		dataLength = [data length];
		dataBytes  = [data bytes];  		
		bytesWrittenSoFar = 0;
		
		do {
			bytesWritten = [self.fileStream write:&dataBytes[bytesWrittenSoFar] maxLength:dataLength - bytesWrittenSoFar];
			assert(bytesWritten != 0);
			if (bytesWritten == -1) {
				[progressAlertView dismissWithClickedButtonIndex:0 animated:FALSE];
				[self stopReceive];
				return;
			} else {
				bytesWrittenSoFar += bytesWritten;
			}
		} while (bytesWrittenSoFar != dataLength);
			
		recvLen += dataLength; 		
		double b1=recvLen*100.00/totalLen;
			
		progressAlertView.message =[NSString stringWithFormat:@"正在下载文件\r\n\r\n 文件大小: %d\r\n 接收字节: %d\r\n\r\n %.2f %% ", totalLen, recvLen, b1, b1];
	}	
}

// 网络错误时触发
- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
{
	[self stopReceive];
}

// 全部数据接收完毕时触发
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
	[self stopReceive];
	
	[progressAlertView dismissWithClickedButtonIndex:0 animated:FALSE];
	if (totalLen == recvLen) {
		if ([self copyTempDBFile]==NO) {
			UIAlertView * alertView = [[UIAlertView alloc] 
									   initWithTitle:@"错误" 
									   message:@"拷贝文件失败\r\n请重启程序，重试下载数据文件。"
									   delegate:nil 
									   cancelButtonTitle:@"确定" 
									   otherButtonTitles:nil];
			[alertView show];
			[alertView release];
		}
		else {
			if (![SQLiteHelper resetDatabase])
			{
				UIAlertView * alertView = [[UIAlertView alloc] 
										   initWithTitle:@"错误" 
										   message:@"数据文件重新打开失败,\r\n请关闭程序重新打开。"
										   delegate:nil 
										   cancelButtonTitle:@"确定" 
										   otherButtonTitles:nil];
				[alertView show];
				[alertView release];
			}
			else {
				UIAlertView * alertView = [[UIAlertView alloc] 
										   initWithTitle:@"提示" 
										   message:[NSString stringWithFormat:@"数据文件更新成功\r\n文件大小： %d",recvLen] 
										   delegate:nil 
										   cancelButtonTitle:@"确定" 
										   otherButtonTitles:nil];
				[alertView show];
				[alertView release];
			}
			
		}
		
	}
	else {
		UIAlertView * alertView = [[UIAlertView alloc] 
								   initWithTitle:@"错误" 
								   message:@"接收文件大小错误"
								   delegate:nil 
								   cancelButtonTitle:@"确定" 
								   otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}	
}

#pragma mark -
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (alertView.tag == 0x8801 && connection != nil) {
		[self stopReceive];
	}
}

- (void)alertViewCancel:(UIAlertView *)alertView
{
}

- (void)willPresentAlertView:(UIAlertView *)alertView
{
}


-(void) dealloc{
	[buffer release];
	[connection release];
	
	[super dealloc];
}

@end
